package com.nd.android.u.ui.widge;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;

import com.common.allCommon.CommonUtils;
import com.product.android.business.manager.MotionEventManager;

/**
 * ClassName:DragListViewController
 * Function: listview中item的拖动控制类（长按拖动）
 * Reason:	 TODO ADD REASON
 * 
 * @author   cb
 * @version  
 * @since    Ver 1.2
 * @Date	 2013	2013-7-8		上午10:07:10
 *
 * @see 	 
 */
public class DragListViewController {
	public interface onEventListener{
		void onClick(int position);
		void onSwitch(int from,int to);
	}
	protected onEventListener mEventListener;
	protected static final float EDGE=0.3f;
	protected WindowManager.LayoutParams mWindowParams;
	protected ImageView mDragImageView;
	protected WindowManager mWindowManager;
	protected Context mContext;
	protected ListView mListView;
	protected boolean mbIsDragging=false;		//是否正在拖动
	protected int mSrcPosition=-1;			//拖动的起始位置（也可表示点击的位置）
	protected int mListViewHeight;			//当前listview的高度，用于判断listview的滚动边界
	protected int mSize=0;					//当前数据源的数据数
	protected Bitmap mBitmap;					//拖动的影像
	protected int mOffset=0;					//偏移量：当前点击的事件的x/y坐标仅相对于当前的listview，要正确的显示当前的影像的位置，必须加上偏移量，该偏移量的数值依赖于当前listview的getTop
	protected int mItemHeight=0;				//listview的item的高
	public DragListViewController(Context context,ListView lv){
		mContext=context;
		mListView=lv;
	}
	
	public void manageList(){
		new manger(mListView);
	}
	
	public void setOnEventListener(onEventListener listener){
		mEventListener=listener;
	}
	
	
	protected class manger extends MotionEventManager{
		public manger(View view) {
			super(view);
		}
		
		@Override
		protected boolean onDown(float x, float y) {
//			Log.d(tag, "down");
			getParams();
			//获取当前位置
			mSrcPosition=mListView.pointToPosition((int)x,(int)y);
			mbIsDragging=false;
			return false;
		}

		protected boolean onMove(float startX, float nowX, float startY, float nowY) {
			if (mSize<=0 || !mbIsDragging){
				return false;
			}
			if (nowY<EDGE*mListViewHeight || nowY>mListViewHeight*(1-EDGE)){
				View view=mListView.getChildAt(0);
				int range=getScrollRange(nowY);
				int pos=mListView.getFirstVisiblePosition();
				mListView.setSelectionFromTop(pos, view.getTop()+range);
			}
			onDrag((int)nowY+mOffset);
			return false;
		};
		
		protected boolean onUp(float x, float y) {
			if (mSize<=0 || !mbIsDragging){
				return false;
			}
			stopDrag();
			int nowPos=mListView.pointToPosition((int)x,(int)y);
			if (y<=0){
				//超出上边界
				nowPos=0;
			}else if(y>mListViewHeight){
				//超出下边界
				nowPos=mSize-1;
			}else if (y>mSize*mItemHeight){
				//在最下面的空白处
				nowPos=mSize-1;
			}else if (nowPos<0 || nowPos>mSize){
				return false;
			}
			//交换位置并刷新
			if (mEventListener!=null){
				mEventListener.onSwitch(mSrcPosition, nowPos);
			}
			return false;
		};
		
		@Override
		protected boolean onLongClick(float x, float y) {
			if (mSize<=0){
				return false;
			}
			if (mSrcPosition<0 || mSrcPosition>mSize){
				return false;
			}
			int first=mListView.getFirstVisiblePosition();
			//找到当前的view
			View view=mListView.getChildAt(mSrcPosition-first);
			if (view.getTag()!=null){
				return false;
			}
			view.setDrawingCacheEnabled(true);
			//获取截图
			mBitmap=view.getDrawingCache();
			mbIsDragging=true;
			//准备拖动
			startDrag(mBitmap,(int)y+mOffset);
			return true;
		}
		
		@Override
		protected boolean onClick() {
			if (mEventListener!=null){
				mEventListener.onClick(mSrcPosition);
			}
			return super.onClick();
		}
	}
	
	/**
	 * @n<b>函数名称</b>     :getScrollRange
	 * @brief 获取滚动的距离
	 * @see
	 * @since    Ver 1.2
	 * @param  @param y
	 * @param  @return
	 * @return int
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-7-5下午3:26:28      
	*/
	protected int getScrollRange(float y){
		int delta=(int)y;
		//获取临界值
		int range=(int) (EDGE*mListViewHeight);
		if (delta>range){
			delta=(mListViewHeight-delta)-range;
		}else{
			delta=range-delta;
		}
		//根据临界值计算滚动的速度，越靠近边界的地方滚动越快
		delta=delta/10;
		return delta;
	}
	
	/**
	 * @n<b>函数名称</b>     :getParams
	 * @brief 获取相关参数
	 * @see
	 * @since    Ver 1.2
	 * @param  
	 * @return void
	 * @<b>作者</b>          :  cb
	 * @<b>创建时间</b>      :  2013-7-5下午3:25:51      
	*/
	protected void getParams(){
		mSize=mListView.getAdapter().getCount();
		if (mSize<=0){
			return;
		}
		mListViewHeight=mListView.getHeight();
		if (mOffset==0){
			mItemHeight=mListView.getChildAt(0).getHeight();
			mOffset=mListView.getTop();
		}
	}
	
	public void startDrag(Bitmap bm, int y) {
		// 释放影像，在准备影像的时候，防止影像没释放，每次都执行一下
		stopDrag();
		mWindowParams = new WindowManager.LayoutParams();
		// 从上到下计算y方向上的相对位置，
		mWindowParams.gravity = Gravity.TOP;
		mWindowParams.x = 0;
		mWindowParams.y = y ;
		mWindowParams.width = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
		mWindowParams.height = android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
		// 下面这些参数能够帮助准确定位到选中项点击位置，照抄即可
		mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
		| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
		| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
		| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		mWindowParams.format = PixelFormat.TRANSLUCENT;
		mWindowParams.windowAnimations = 0;
		// 把影像ImagView添加到当前视图中
		ImageView imageView = new ImageView(mContext);
		imageView.setImageBitmap(bm);
		mWindowManager = (WindowManager) mContext.getSystemService("window");
		mWindowManager.addView(imageView, mWindowParams);
		// 把影像ImageView引用到变量drawImageView，用于后续操作(拖动，释放等等)
		mDragImageView = imageView;
	}
	
	public void onDrag(int y) {
		//更新位置
		if (mDragImageView != null) {
			mWindowParams.alpha = 0.8f;
			mWindowParams.y = y;
			mWindowManager.updateViewLayout(mDragImageView, mWindowParams);
		}
	}
	
	public void stopDrag() {
		//释放
		if (mDragImageView != null) {
			mWindowManager.removeView(mDragImageView);
			mDragImageView = null;
		}
	}
	
	public void recycle(){
		CommonUtils.recycleBitmap(mBitmap);
	}
}
